package com.carlyang.jspservlet.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/*
 * 	1，request作为参数传人，已知，需要在 Servlet 中获取 session,application
 *	2，客户端跳转 response.sendRedirect("目标地址");request信息无法带到新页面，session和application信息可以。
 *	3，服务器跳转：RequestDispatcher rd=request.getRequestDispatcher("目标地址"); rd.forward(request, response);
 *	服务器跳转，request,session,application都可以传递到新页面
 * */
public class ForwardServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		System.out.println("doGet");
		this.doPost(request, response);//get请求交给Post处理
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		System.out.println("doPost");
		request.setAttribute("requestKey", "request值");
		HttpSession session = request.getSession();//获取Session
		session.setAttribute("sessionKey", "session值");
		ServletContext application = this.getServletContext();//获取application
		application.setAttribute("applicationKey", "application值");
		//服务器跳转/转发    先获取request分发，再在分发中调用forward
		RequestDispatcher requestDispatcher = request.getRequestDispatcher("chapter3/target.jsp");
		requestDispatcher.forward(request, response);
	}

	@Override
	public void destroy() {
		System.out.println("destroy");
	}

	@Override
	public void init() throws ServletException {
		System.out.println("Servlet初始化init");
	}
	
}
